package com.mlm.mlmapp.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.Receiver;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.DimensionRes;
import org.androidannotations.annotations.res.DrawableRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.OnScrollListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.Constants;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.activity.layoutmanager.SyGridLayoutManager;
import com.mlm.mlmapp.adapter.view.AQProgressDialog;
import com.mlm.mlmapp.adapter.view.BuyPointsDialog;
import com.mlm.mlmapp.adapter.view.GridMarginDecoration;
import com.mlm.mlmapp.adapter.view.listener.DialogListener;
import com.mlm.mlmapp.adapter.view.listener.OnRecyclerViewScrollListener;
import com.mlm.mlmapp.adapter.view.listener.onBuyClickListner;
import com.mlm.mlmapp.animation.RecyclAnimation;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;
import com.mlm.mlmapp.utils.PayResult;
import com.mlm.mlmapp.wxapi.WXPayEntryActivity;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

@EActivity(R.layout.buy_point_list)
public class BuyPointListActivity extends BaseActivity implements HTTPCons,onBuyClickListner {

	@Pref
	Prefs_ pref;
	@DimensionRes(R.dimen.recyclerview_mycomments_space)
	float commentImagesMargin;
	@DimensionRes
	float comments_images_edge;
	@ColorRes
	int red;
	@ColorRes
	int lightgreytext;
	@ColorRes
	int blacktext;
	public String currentJson = "";
	private AQuery aq;
	private PointListAdapter adapter;
	List<JSONObject> pointListDataset;
	@ViewById
	RecyclerView rv_coupons;
	@Extra
	String couponid;
	@Extra
	String id;
	@DrawableRes
	Drawable grey_edge_btn_long;
	int integralId;
	String type;
	BuyPointsDialog dialog;
	int currPage=2;


	String outtradeno;
	@AfterViews
	public void init() {

			String title = getTitle().toString();
		if (!"".equals(title)) {
			((TextView) this.findViewById(R.id.tv_title)).setText(title);
		}

		if ("0".equals(pref.loginID().get())) {
			LoginActivity_.intent(this).startForResult(REQUEST_CODE);
			return;
		}
		aq = new AQuery(this);
		aq.hardwareAccelerated11();
		pointListDataset = new ArrayList<>();
		final GridLayoutManager layoutManager = new SyGridLayoutManager(this, 1);
		rv_coupons.setLayoutManager(layoutManager);
		rv_coupons
				.addItemDecoration(new GridMarginDecoration(this, 0, 0, 0, 0));
		rv_coupons.setItemAnimator(new RecyclAnimation());
		adapter = new PointListAdapter(BuyPointListActivity.this, pointListDataset);
		rv_coupons.setAdapter(adapter);
		getPointList(0);
//		rv_coupons.setOnScrollListener(new OnRecyclerViewScrollListener() {
//
//			@Override
//			public void onLoadMore() {
//				// TODO Auto-generated method stub
//				Log.d("sort","onLoadMore");
//				getPointList(currPage);
//				currPage++;
//			}
//		});

	}


	public void wechatPay(JSONObject json) {

		// String url =
		// "http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=android";
		try {
			if (null != json && !json.has("retcode")) {
				PayReq req = new PayReq();
				// req.appId = "wxf8b4f85f3a794e77"; // 测试用appId

				req.appId = json.getString("appid");

				req.partnerId = json.getString("partnerid");
				req.prepayId = json.getString("prepayid");
				this.outtradeno=req.prepayId;
				req.nonceStr = json.getString("noncestr");
				req.timeStamp = json.getString("timestamp");
				req.packageValue = "Sign=WXPay";
				req.sign = json.getString("sign");
				req.extData = "app data"; // optional

				// 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信

				IWXAPI wxApi = WXAPIFactory.createWXAPI(BuyPointListActivity.this,
						req.appId, true);
				wxApi.registerApp(req.appId);
				if (!wxApi.isWXAppInstalled()) {
					Toast.makeText(BuyPointListActivity.this, "没有安装微信",
							Toast.LENGTH_SHORT).show();
					return;
				}
				if (!wxApi.isWXAppSupportAPI()) {
					Toast.makeText(BuyPointListActivity.this, "当前版本不支持支付功能",
							Toast.LENGTH_SHORT).show();
					return;
				}
				wxApi.sendReq(req);
			} else {
				Toast.makeText(BuyPointListActivity.this,
						"返回错误" + json.getString("retmsg"), Toast.LENGTH_SHORT)
						.show();
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}




	private static final int SDK_PAY_FLAG = 1;
	private static final int SDK_CHECK_FLAG = 2;
	public void pay(final String payInfo) {
		/**
		 * 完整的符合支付宝参数规范的订单信息
		 */

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(BuyPointListActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo, true);
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case SDK_PAY_FLAG: {
					PayResult payResult = new PayResult((String) msg.obj);
					/**
					 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
					 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
					 * docType=1) 建议商户依赖异步通知
					 */
					String resultInfo = payResult.getResult();// 同步返回需要验证的信息
					String resultStatus = payResult.getResultStatus();
//					Log.d("sort", "resultInfo" + resultInfo);
//					Log.d("sort", "resultStatus" + resultStatus);
					// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
					dialog.dismiss();
					if (TextUtils.equals(resultStatus, "9000")) {
						Toast.makeText(BuyPointListActivity.this, "支付成功",
								Toast.LENGTH_SHORT).show();
						pointNotify();

					} else {
						// 判断resultStatus 为非"9000"则代表可能支付失败
						// "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
						if (TextUtils.equals(resultStatus, "8000")) {
							Toast.makeText(BuyPointListActivity.this, "支付结果确认中",
									Toast.LENGTH_SHORT).show();
							pointNotify();
						} else {
							// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
							Toast.makeText(BuyPointListActivity.this, "支付失败",
									Toast.LENGTH_SHORT).show();
						}


					}

					break;
				}
				case SDK_CHECK_FLAG: {
					Toast.makeText(BuyPointListActivity.this, "检查结果为：" + msg.obj,
							Toast.LENGTH_SHORT).show();
					break;
				}
				default:
					break;
			}
		}
	};
	@Receiver(actions = WXPayEntryActivity.PAY_FINISH, registerAt = Receiver.RegisterAt.OnCreateOnDestroy)
	protected void onPayFinish(Intent intent) {
		if(dialog!=null){

			dialog.dismiss();
		}
	}
	@Override
	public void onClick(int integralId,int money) {
		this.integralId=integralId;

		dialog=new BuyPointsDialog(this, new DialogListener() {
			@Override
			public void onApply(JSONObject obj, String clazz) {
				BuyPointListActivity.this.type=clazz;
				try {
					if(Integer.valueOf(clazz)==BuyPointsDialog.PAYMENT_TYPE_ALIPAY) {
						String a=getJsonArray(obj, "errors").getString(0);
						String[] array=a.split("&");
						for (String temp:array){
							if(temp.contains("out_trade_no")){
								String no=temp.split("=")[1];
								BuyPointListActivity.this.outtradeno=no.substring(1, no.length() - 1);


							}

						}

						pay(a);
					}else
						wechatPay(new JSONObject(getJsonArray(obj,"errors").getString(0)));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancel() {

			}
		},integralId,money,pref.loginID().get());
		dialog.show();
	}


	void pointNotify(){

		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
		pairs.add(new BasicNameValuePair("integralId", integralId + ""));
		pairs.add(new BasicNameValuePair("payType", type));
		String url;

		CommonUtils.postRequest(points_notify, aq,
				new AjaxCallback<JSONObject>() {
					@Override
					public void callback(String url, JSONObject obj,
										 AjaxStatus status) {
						if (status.getCode() == -101) {
							Toast.makeText(aq.getContext(), "网络异常,请检查网络",
									Toast.LENGTH_SHORT);
							return;
						}
						if (status.getCode() == -103) {
							Toast.makeText(aq.getContext(), "用户信息异常，请联系客服",
									Toast.LENGTH_SHORT).show();
						} else {
							if (status.getCode() != 200) {
								Toast.makeText(aq.getContext(),
										"网络异常:" + status.getCode(),
										Toast.LENGTH_SHORT).show();
							} else {

								try {
									if (obj.getBoolean("isSuccess")) {


									} else {
										Toast.makeText(aq.getContext(),
												obj.getString("errors"),
												Toast.LENGTH_SHORT).show();
									}
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}
					}

				}, pairs);
	}
	void getPointList(final int page) {
		aq.progress(new AQProgressDialog(this)).ajax(CommonUtils.getURLStringParams(get_buy_point_list, new HashMap<String, String>()),
				JSONArray.class,
				new AjaxCallback<JSONArray>() {

					@Override
					public void callback(String url, JSONArray array,
										 AjaxStatus status) {

						if (status.getCode() == -101) {
							Toast.makeText(aq.getContext(), "网络异常,请检查网络",
									Toast.LENGTH_SHORT);
							return;
						}
						// TODO Auto-generated method stub
						if (status.getCode() == 200) {

							for (int i = 0; i < array.length(); i++) {
								JSONObject obj;
								try {
									obj = array.getJSONObject(i);
									pointListDataset.add(obj);
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

							}
							adapter.notifyDataSetChanged();

						} else if (status.getCode() == 500) {
							Toast.makeText(aq.getContext(),
									"服务器异常:" + status.getCode(),
									Toast.LENGTH_SHORT).show();
						} else {
							Toast.makeText(aq.getContext(),
									"网络异常:" + status.getCode(),
									Toast.LENGTH_SHORT).show();

						}
					}

				});
	}

	class PointListAdapter extends
			RecyclerView.Adapter<RecyclerView.ViewHolder> {
		private List<JSONObject> array;

		public PointListAdapter(Context con, List<JSONObject> array) {
			this.array = array;

		}

		@Override
		public int getItemCount() {
			return array.size();
		}

		public boolean isPositionHeader(int position) {
			return position == 0;
		}

		@Override
		public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
				int viewType) {
			// TODO Auto-generated method stub
			final PointViewHolder holder = new PointViewHolder(LayoutInflater
					.from(BuyPointListActivity.this).inflate(
							R.layout.buy_point_list_item, parent, false));
			return holder;

		}

		@Override
		public void onBindViewHolder(RecyclerView.ViewHolder holder,
				int position) {
			// TODO Auto-generated method stub
			final PointViewHolder vholder = (PointViewHolder) holder;
			final JSONObject temp = array.get(position);
			int points = getJsonInt(temp, "integral");
			final int price = getJsonInt(temp, "fund");
			int status = getJsonInt(temp, "status");
			final int id = getJsonInt(temp, "id");
			String url = getJsonString(temp, "url");
			aq.id(vholder.iv_coin).image(
					url, true, true,
					0, 0, null, Constants.FADE_IN);
			vholder.tv_points.setText(points+"积分");
			vholder.tv_price.setText(getString(R.string.money,
					price));
			vholder.btn_buy.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					BuyPointListActivity.this.onClick(id,price);
				}
			});

		}

		public class PointViewHolder extends RecyclerView.ViewHolder {
			TextView tv_points;
			TextView tv_price;
			Button btn_buy;
			ImageView iv_coin;
			public PointViewHolder(View itemView) {
				super(itemView);
				this.tv_points = (TextView) itemView.findViewById(R.id.tv_points);
				this.tv_price = (TextView) itemView.findViewById(R.id.tv_price);
				this.btn_buy = (Button) itemView
						.findViewById(R.id.btn_buy);
				this.iv_coin=(ImageView) itemView.findViewById((R.id.iv_coin));

			}
		}
	}

	@Click
	void btn_back() {
		onBackPressed();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		Intent data = new Intent();
		setResult(RESULT_CANCELED, data);
		this.finish();
	}

}
